package com.okay.at

import android.content.Context
import android.text.Spannable
import android.text.SpannableString
import com.okay.testclass.R
import com.okay.util.DensityUtils
import java.util.ArrayList
import java.util.regex.Pattern
/**

 * create nano on 2022/2/24 11:19

 */
class CheckAtUtil {
    constructor()


    /**
     * 判断有没有@人的事件
     */
    fun isCheckName(content: String):Boolean{
        val pattern = Pattern.compile("@([^@\\x22]+)\\u200b")
        val matcher = pattern.matcher(content)
        return matcher.find()
    }

    /**
     * 这个是从数据里面查找出@人的数据 并进行替换
     */
    fun getCheckName(context: Context, content: String, textSize: Float): SpannableString? {
        val pattern = Pattern.compile("@([^@\\x22]+)\\u200b")
        val list: MutableList<ATTeacher> = ArrayList()
        val matcher = pattern.matcher(content)
        while (matcher.find()) {
            list.add(ATTeacher(matcher.group(), matcher.start(), matcher.end()))
        }

        return if (list.size > 0) {
            getSpan(context, content, list, textSize)
        } else {
            SpannableString(content)
        }
    }

    /**
     * 这个是直接点击需要@的人，所以只需要添加@re的名称
     * usrStr 内容
     * textSize 字号
     *
     */
    fun conversionDraw(context: Context?, usrStr: String, textSize: Float): SpannableString? {
        val list: MutableList<ATTeacher> = ArrayList()
        list.add(ATTeacher(usrStr, 0, usrStr.length))
        return getSpan(context, usrStr, list, textSize)
    }

    /**
     * 将文字转换成自定义view添加进span
     */
    fun getSpan(
        context: Context?,
        content: String,
        list: MutableList<ATTeacher>,
        textSize: Float
    ): SpannableString? {
        val spanText = SpannableString(content)

        for (index in list) {
            val span = RadiusBackgroundSpan(
                context,
                R.color.color_15B0D6,
                DensityUtils.sp2px(context, textSize),
                5,
                index.ATname
            )
            spanText.setSpan(span, index.start, index.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        }

        //        //添加点击事件
//        ClickableSpan clickableSpan = new ClickableSpan() {
//            @Override
//            public void onClick(View widget) {
//                Toast.makeText(context, usrStr, Toast.LENGTH_SHORT).show();
//            }
//        };
//        spanText.setSpan(clickableSpan,0, spanText.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return spanText
    }
}